﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using XiaoMan.API.Filter;
using XiaoMan.BLL;
using XiaoMan.Model.Models;
using XiaoMan.Service;

namespace XiaoMan.API.Controllers
{
    [RoutePrefix("api/users")]
    public class UsersController : ApiBaseController
    {
        Sys_UsersService sus = new Sys_UsersService();
        Sys_UserInfoService suis = new Sys_UserInfoService();
        Sys_UserAndDiseaseService suds = new Sys_UserAndDiseaseService();
        Sys_DiseaseService sds = new Sys_DiseaseService();
        Sys_AdminUserAndDiseaseService sauds = new Sys_AdminUserAndDiseaseService();
        Sys_RelationService srs = new Sys_RelationService();

        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns></returns>
        [Route("getusers")]
        [HttpPost]
        public IHttpActionResult GetUsers()
        {
            var userid = Convert.ToInt32(Request.Headers.GetValues("userid").FirstOrDefault());
            List<Sys_Users> users = sus.GetList();
            return ApiSuccess(users);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <param name="oldpwd">新密码</param>
        /// <param name="newpwd">老密码</param>
        /// <returns></returns>
        [Route("updatepwd")]
        [HttpPost]
        public IHttpActionResult updatePwd(dynamic obj)
        {
            var token = Request.Headers.Authorization.Parameter;
            int userid = Convert.ToInt32(Request.Headers.GetValues("userid").FirstOrDefault());
            string oldPWD = Convert.ToString(obj.oldpwd);
            string newPWD = Convert.ToString(obj.newpwd);
            //此处也可以根据token 去缓存取 
            Sys_Users user = sus.GetUserByID(userid);
            if (user.Password != MD5Manager.Gen_MD5(oldPWD))
            {
                return ApiFail("原密码错误！");
            }
            user.Password = MD5Manager.Gen_MD5(newPWD);
            string message = string.Empty;
            if (sus.EditUser(user))
            {
                CacheManager.Remove(token);
                return ApiSuccess(new { msg = "修改成功，请重新登陆" });
            }
            else
            {
                return ApiFail("修改失败！");
            }
        }


        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [Route("postlogoff")]
        [HttpPost]
        public IHttpActionResult postLogOff(dynamic obj)
        {
            var token = Request.Headers.Authorization.Parameter;
            if (!string.IsNullOrEmpty(token))
            {
                string strUserID = Convert.ToString(obj.UserID);
                int userid = 0;
                if (!string.IsNullOrEmpty(strUserID) && int.TryParse(strUserID, out userid) && userid > 0)
                {
                    Sys_Users user = sus.GetUserByID(userid);
                    if (user != null)
                    {
                        CacheManager.Remove(token);
                        return ApiSuccess("退出成功！");
                    }
                }
            }
            return ApiFail("退出失败！");
        }

        /// <summary>
        /// 获取用户详细信息
        /// </summary>
        /// <returns></returns>
        [Route("getuserinfo")]
        [HttpPost]
        public IHttpActionResult getUserInfo(dynamic obj)
        {
            string strUserID = Convert.ToString(obj.UserID);
            int userid = 0;
            if (!string.IsNullOrEmpty(strUserID) && int.TryParse(strUserID, out userid) && userid > 0)
            {
                Sys_UserInfo userInfo = suis.GetUserInfoByUserID(userid);
                if (userInfo != null)
                {
                    return ApiSuccess(userInfo);
                }
            }
            return ApiFail("获取用户详细信息失败,请检查用户ID是否正确");
        }


        /// <summary>
        /// 编辑用户绑定平台账号
        /// </summary>
        /// <returns></returns>
        [Route("posteditbinding")]
        [HttpPost]
        public IHttpActionResult postEditBinding(dynamic obj)
        {
            string strNumber = Convert.ToString(obj.Number);
            string strNumberType = Convert.ToString(obj.NumberType);
            int numberType = 0;
            if (!string.IsNullOrEmpty(strNumber) && !string.IsNullOrEmpty(strNumberType) && int.TryParse(strNumberType, out numberType) && numberType > 0 && numberType <= 3)
            {
                int userid = Convert.ToInt32(Request.Headers.GetValues("userid").FirstOrDefault());
                Sys_Users user = sus.GetUserByID(userid);
                if (user != null)
                {
                    if (numberType == 1)
                    {
                        user.QQ = strNumber;
                    }
                    else if (numberType == 2)
                    {
                        user.WeChat = strNumber;
                    }
                    else
                    {
                        user.WeiBo = strNumber;
                    }
                    sus.Update(user);
                    return ApiSuccess("绑定成功！");
                }
            }
            return ApiFail("绑定失败！");
        }

        /// <summary>
        /// 用户关注圈子或取消关注圈子，1是关注该圈子，0是取消关注该圈子
        /// </summary>
        /// <returns></returns>
        [Route("postuserfollowornot")]
        [HttpPost]
        public IHttpActionResult postUserFollowOrNot(dynamic obj)
        {
            string strUserID = Convert.ToString(obj.UserID);
            string strDiseaseID = Convert.ToString(obj.DiseaseID);
            string strFollowType = Convert.ToString(obj.FollowType);
            if (!string.IsNullOrEmpty(strUserID) && !string.IsNullOrEmpty(strDiseaseID) && !string.IsNullOrEmpty(strFollowType))
            {
                int userid = 0;
                int diseaseID = 0;
                int followType = 0;
                if (int.TryParse(strUserID, out userid) && userid > 0 && int.TryParse(strDiseaseID, out diseaseID) && diseaseID > 0 && int.TryParse(strFollowType, out followType) && (followType == 0 || followType == 1))
                {
                    Sys_Users user = sus.GetUserByID(userid);
                    Sys_Disease disease = sds.GetDiseaseByID(diseaseID);
                    if (user != null && disease != null)
                    {
                        Sys_UserAndDisease userAndDisease = suds.GetUserAndDisease(userid, diseaseID);
                        if (userAndDisease != null)
                        {
                            if (followType == 0)
                            {
                                //0是取消关注该圈子
                                suds.DeleteUserAndDisease(userAndDisease);
                                if (disease.MemberCount > 0)
                                {
                                    disease.MemberCount -= 1;
                                    sds.EditDisease(disease);
                                }
                            }
                        }
                        else
                        {
                            if (followType == 1)
                            {
                                //1是关注该圈子
                                userAndDisease = new Sys_UserAndDisease();
                                userAndDisease.DiseaseID = diseaseID;
                                userAndDisease.DiseaseName = disease.DiseaseName;
                                userAndDisease.UserID = userid;
                                userAndDisease.UserNikeName = user.NickName;
                                suds.AddUserAndDisease(userAndDisease);

                                disease.MemberCount += 1;
                                sds.EditDisease(disease);
                            }
                        }
                        return ApiSuccess("操作成功！");
                    }
                }
            }
            return ApiFail("操作失败！");
        }


        /// <summary>
        /// 用户是否管理该疾病
        /// </summary>
        /// <returns></returns>
        [Route("postusermanagementdiseaseornot")]
        [HttpPost]
        public IHttpActionResult postUserManagementDiseaseOrNot(dynamic obj)
        {
            string strUserID = Convert.ToString(obj.UserID);
            string strDiseaseID = Convert.ToString(obj.DiseaseID);
            string strManagementType = Convert.ToString(obj.ManagementType);
            if (!string.IsNullOrEmpty(strUserID) && !string.IsNullOrEmpty(strDiseaseID) && !string.IsNullOrEmpty(strManagementType))
            {
                int userid = 0;
                int diseaseID = 0;
                int managementType = 0;
                if (int.TryParse(strUserID, out userid) && userid > 0 && int.TryParse(strDiseaseID, out diseaseID) && diseaseID > 0 && int.TryParse(strManagementType, out managementType) && (managementType == 0 || managementType == 1))
                {
                    Sys_Users user = sus.GetUserByID(userid);
                    Sys_Disease disease = sds.GetDiseaseByID(diseaseID);
                    if (user != null && disease != null)
                    {
                        Sys_AdminUserAndDisease adminUserAndDisease = sauds.GetAdminUserAndDisease(userid, diseaseID);
                        if (adminUserAndDisease != null)
                        {
                            if (managementType == 0)
                            {
                                //0是取消管理该疾病
                                sauds.DeleteAdminUserAndDisease(adminUserAndDisease);
                                List<Sys_AdminUserAndDisease> adminUserAndDiseases = sauds.GetListByUserID(userid);
                                if ((adminUserAndDiseases == null || adminUserAndDiseases.Count <= 0) && user.UserType == 2)
                                {
                                    user.UserType = 1;
                                    sus.Update(user);
                                }
                            }
                        }
                        else
                        {
                            if (managementType == 1)
                            {
                                //1是管理该疾病
                                adminUserAndDisease = new Sys_AdminUserAndDisease();
                                adminUserAndDisease.DiseaseID = diseaseID;
                                adminUserAndDisease.DiseaseName = disease.DiseaseName;
                                adminUserAndDisease.UserID = userid;
                                adminUserAndDisease.UserNikeName = user.NickName;
                                sauds.AddAdminUserAndDisease(adminUserAndDisease);

                                if (user.UserType == 1)
                                {
                                    user.UserType = 2;
                                    sus.Update(user);
                                }
                            }
                        }

                        return ApiSuccess("操作成功！");
                    }
                }
            }
            return ApiFail("操作失败！");
        }


        /// <summary>
        /// 用户和用户之间关注和粉丝的关系，1是关注，2是取消关注
        /// </summary>
        /// <returns></returns>
        [Route("postuserrelation")]
        [HttpPost]
        public IHttpActionResult postUserRelation(dynamic obj)
        {
            string strUserID = Convert.ToString(obj.UserID);
            //string strDiseaseID = Convert.ToString(obj.DiseaseID);
            string strFollowUserID = Convert.ToString(obj.FollowUserID);
            string strFollowType = Convert.ToString(obj.FollowType);
            if (!string.IsNullOrEmpty(strUserID) && !string.IsNullOrEmpty(strFollowUserID) && !string.IsNullOrEmpty(strFollowType))
            {
                int userid = 0;
                //int diseaseID = 0;
                int followType = 0;
                int followUserID = 0;
                if (int.TryParse(strUserID, out userid) && userid > 0 && int.TryParse(strFollowUserID, out followUserID) && followUserID > 0 && int.TryParse(strFollowType, out followType) && (followType == 1 || followType == 2))
                {
                    Sys_UserInfo userInfo = suis.GetUserInfoByUserID(userid);
                    Sys_UserInfo followUserInfo = suis.GetUserInfoByUserID(followUserID);
                    if (userInfo != null && followUserInfo != null)
                    {
                        Sys_Relation relation = srs.GetRelation(userid, followUserID);
                        if (relation != null)
                        {
                            if (followType == 2)
                            {
                                //2是取消关注
                                srs.DeleteRelation(relation);
                                if (userInfo.FollowCount > 0)
                                {
                                    userInfo.FollowCount -= 1;
                                    suis.Update(userInfo);
                                }
                                if (followUserInfo.FansCount > 0)
                                {
                                    followUserInfo.FansCount -= 1;
                                    suis.Update(followUserInfo);
                                }
                            }
                        }
                        else
                        {
                            if (followType == 1)
                            {
                                //1是关注
                                relation = new Sys_Relation();
                                relation.FollowUserID = followUserID;
                                relation.GroupNameID = 0;
                                relation.UserID = userid;
                                srs.Add(relation);

                                userInfo.FollowCount += 1;
                                suis.Update(userInfo);

                                followUserInfo.FansCount += 1;
                                suis.Update(followUserInfo);
                            }
                        }
                        return ApiSuccess("操作成功！");
                    }
                }
            }
            return ApiFail("操作失败！");
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="obj"></param>
        [Route("postuserregister")]
        [HttpPost]
        public IHttpActionResult postUserRegister(dynamic obj)
        {
            string strUserName = Convert.ToString(obj.UserName);
            string strPassword = Convert.ToString(obj.Password);
            string strMainDiseaseID = Convert.ToString(obj.MainDiseaseID);
            string strIdentifyingCode = Convert.ToString(obj.IdentifyingCode);
            if (!string.IsNullOrEmpty(strUserName) && !string.IsNullOrEmpty(strPassword) && !string.IsNullOrEmpty(strMainDiseaseID) && !string.IsNullOrEmpty(strIdentifyingCode))
            {
                var smsCode = CacheManager.Get<String>(strUserName);
                if (smsCode != null && strIdentifyingCode == smsCode.ToString())
                {
                    int mainDiseaseID = 0;
                    if (int.TryParse(strMainDiseaseID, out mainDiseaseID) && mainDiseaseID > 0)
                    {
                        Sys_Users userInfo = sus.GetUserByUserName(strUserName);
                        if (userInfo != null)
                        {
                            return ApiFail("该账号已存在！");
                        }
                        else
                        {
                            userInfo = new Sys_Users();
                            userInfo.CreateTime = DateTime.Now;
                            userInfo.IsDelFlag = false;
                            userInfo.MainDiseaseID = mainDiseaseID;
                            userInfo.Mobile = strUserName;
                            userInfo.Password = MD5Manager.Gen_MD5(strPassword);
                            userInfo.NickName = strUserName;
                            userInfo.UserName = strUserName;
                            userInfo.UserType = 1;
                            if (sus.Add(userInfo))
                            {
                                userInfo = sus.GetUserByUserName(strUserName);
                                return ApiSuccess(userInfo);
                            }
                            else
                            {
                                return ApiFail("注册失败！");
                            }
                        }
                    }
                    else
                    {
                        return ApiFail("疾病的ID格式错误！");
                    }
                }
                else
                {
                    return ApiFail("验证码不正确！");
                }
            }
            else
            {
                return ApiFail("缺少参数！");
            }
        }
    }
}
